package com.jerry.gateway.zuul.controller;

import com.google.common.collect.Maps;
import com.jerry.common.bean.User;
import com.jerry.gateway.zuul.service.AggregationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import rx.Observable;
import rx.Observer;

import java.util.HashMap;

@RestController
@RequestMapping("/aggregate")
public class AggregationController {

    @Autowired
    private AggregationService aggregationService;

    @GetMapping("/object/{userId}")
    public DeferredResult<HashMap<String, User>> aggregateObject(@PathVariable("userId") Long userId) {
        Observable<HashMap<String, User>> result = this.aggregateObservable(userId);
        return this.toDeferredResult(result);
    }

    public Observable<HashMap<String, User>> aggregateObservable(Long userId) {
        // 合并两个或者多个Observables发射出的数据项，根据指定的函数变换它们
        return Observable.zip(
                this.aggregationService.getUserById(userId),
                this.aggregationService.getOrderUserByUserId(userId),
                (user, orderUser) -> {
                    HashMap<String, User> map = Maps.newHashMap();
                    map.put("user", user);
                    map.put("orderUser", orderUser);
                    return map;
                }
        );
    }

    public DeferredResult<HashMap<String, User>> toDeferredResult(Observable<HashMap<String, User>> details) {
        DeferredResult<HashMap<String, User>> result = new DeferredResult<>();
        // 订阅
        details.subscribe(new Observer<HashMap<String, User>>() {
            @Override
            public void onCompleted() {
                System.out.println("完成...");
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("发生错误..." + throwable);
            }

            @Override
            public void onNext(HashMap<String, User> movieDetails) {
                result.setResult(movieDetails);
            }
        });
        return result;
    }

}
